package com.icebergteam.warfacewidget.data.sql;

import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.core.LogManager;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public abstract class BasicTable {
	public static final String className = BasicTable.class.getCanonicalName();
	
	public long insert(ContentValues cv){
		SQLiteDatabase db = AppManager.getDatabase().getWritableDatabase();
		if(db != null && db.isOpen()){
			return AppManager.getDatabase().getWritableDatabase().insert(getTableName(), null, cv);
		}
		else{
			return -1;
		}
	}
	
	public long updateOrInsert(ContentValues cv) {
		SQLiteDatabase db = AppManager.getDatabase().getWritableDatabase();
		if(db != null && db.isOpen()){			 
			 long rowId = 0;
			 db.beginTransaction();
			 try {
				 WhereWrapper where = getUpdateWhere(cv);
				 int affected = db.update(getTableName(), cv, where.getWhere(), where.getValues());
				 if (affected == 0) {
					 rowId = db.insert(getTableName(), null, cv);
				 }
				 db.setTransactionSuccessful();
			 } catch (SQLException ex) {
				LogManager.LogE(className, LogManager.getExecuteMethodName(), ex.getLocalizedMessage());
				ex.printStackTrace();
			 } finally {
			       db.endTransaction();
			 }
			 return rowId;
		}
		return -1;
	}
	
	protected abstract WhereWrapper getUpdateWhere(ContentValues cv);
	
	public int getCount() {
		SQLiteDatabase db = AppManager.getDatabase().getWritableDatabase();
		if(db != null && db.isOpen()) {
			Cursor dataCount = db.rawQuery("select count(*) from " + getTableName(), null);
			dataCount.moveToFirst();
						
			if(dataCount!=null){
				return dataCount.getInt(0);
			}
		}
		return -1;		
	}
	
	public int getCount(String sel) throws SQLException{
		SQLiteDatabase db = AppManager.getDatabase().getWritableDatabase();
		if(db != null && db.isOpen()){
			
			Cursor cur = db.rawQuery(String.format("select count(*) from %s" + ((sel!= null)? (" where " + sel):""), NewsTable.TABLE_NAME), null);
			cur.moveToFirst();
			
			if(cur!=null){
				return cur.getInt(0);
			}
		}
		return -1;
	}

	protected abstract String getTableName();
}
